#### Figure 3: Democratic Norm Violations + Political Violence Support by PID Strength/Affpol ####

# Libraries
# library(here)
# library(rio)
# library(tidyverse)
# library(ggthemes)
# library(srvyr)
# library(lubridate)

# data_pnas = import(here("Data","data_pnas.rds"))
# source(here("Code","Functions","funcs_theme.R"))

violence_ind = paste0("violence",3:6,"re")
norm_ind = paste0("norm_",c("judges","polling","censorship","loyalty"),"re")

#### PID Strength ####

cs_summary_strength = data_pnas |> 
  filter(pid7 %in% c(1:3,5:7)) |>
  mutate(pid_str = case_when(
    pid7 == 1 ~ "Strong Democrat",
    pid7 %in% 2:3 ~ "Weak/Lean Democrat",
    pid7 %in% 5:6 ~ "Weak/Lean Republican",
    pid7 == 7 ~ "Strong Republican"
  )) |>
  select(pid_str, all_of(c(violence_ind, norm_ind)),
         uid, weight) |> 
  pivot_longer(-c("pid_str","uid","weight"), names_to = "var", values_to = "val") |> 
  as_survey_design(ids = uid, weights = weight) |> 
  group_by(pid_str, var) |> 
  summarise(val_sum = survey_mean(val, na.rm = T, vartype = "ci")) |> 
  ungroup() |> 
  mutate(var_typ = ifelse(str_detect(var,"norm"), "Democratic\nNorms", "Violence"),
         var = recode_factor(var,
                             norm_pollingre = "Reduce outparty\npolling stations",
                             norm_loyaltyre = "More loyal to party\nthan Constitution\nin contested elections",
                             norm_judgesre = "Ignore outparty\ncourt decisions",
                             norm_executivere = "President should\ncircumvent congress",
                             norm_censorshipre = "Censor partisan\nmedia",
                             violence6re = "Murder",
                             violence5re = "Assault with\ndeadly weapon",
                             violence4re = "Arson",
                             violence3re = "Assault",
                             violence2re = "Vandalism",
                             violence1re = "Protest without\npermit") 
  ) |> 
  separate(pid_str, into = c("strength", "party"), sep = " ")

fig_3a = cs_summary_strength |> 
  ggplot(aes(x = val_sum, y = var,
             group = interaction(strength, party),
             label = paste0(round(val_sum,3)*100,"%"))) +
  geom_pointrange(aes(xmin = val_sum_low,
                      xmax = val_sum_upp,
                      color = party,
                      shape = strength),
                  position = position_dodge(0.8)) +
  geom_text(aes(x = val_sum + .28),
            position = position_dodge(0.8),
            size = rel(3)) +
  facet_wrap(~ var_typ, scales = "free") +
  scale_color_manual(name = "Party",
                     values = c("blue","red"),
                     guide = guide_legend(title.position = 'top')) +
  scale_shape_manual(name = "PID Strength",
                     values = 16:17,
                     guide = guide_legend(title.position = 'top')) +
  scale_x_continuous(labels = scales::percent,
                     limits = c(0,1),
                     breaks = c(0,.5,1)) +
  labs(x = "Percent Support",
       y = NULL) +
  theme_prl(base_family = "Helvetica") +
  theme(legend.box = 'horizontal',
        legend.direction = 'vertical',
        axis.text.x = element_text(size = rel(.92)),
        legend.spacing.y = unit(.01, 'cm'),
        legend.margin=margin(0,0,0,0),
        legend.box.margin=margin(-5,-5,-5,-5))

#### Affpol Bin ####

cs_summary_affpol = data_pnas |> 
  filter(pid %in% c("Democrat","Republican"),
         !is.na(affpolre)) |> # Just D/R
  select(affpolre, all_of(c(violence_ind, norm_ind)),
         uid, weight) |> 
  pivot_longer(-c("affpolre","uid","weight"), names_to = "var", values_to = "val") |> 
  as_survey_design(ids = uid, weights = weight) |> 
  group_by(affpolre, var) |> 
  summarise(val_sum = survey_mean(val, na.rm = T, vartype = "ci")) |> 
  ungroup() |> 
  mutate(var_typ = ifelse(str_detect(var,"norm"), "Democratic\nNorms", "Violence"),
         var = recode_factor(var,
                             norm_pollingre = "Reduce outparty\npolling stations",
                             norm_loyaltyre = "More loyal to party\nthan Constitution\nin contested elections",
                             norm_judgesre = "Ignore outparty\ncourt decisions",
                             norm_executivere = "President should\ncircumvent congress",
                             norm_censorshipre = "Censor partisan\nmedia",
                             violence6re = "Murder",
                             violence5re = "Assault with\ndeadly weapon",
                             violence4re = "Arson",
                             violence3re = "Assault",
                             violence2re = "Vandalism",
                             violence1re = "Protest without\npermit") 
  )

fig_3b = cs_summary_affpol |> 
  ggplot(aes(x = val_sum, y = var,
             group = affpolre,
             label = paste0(round(val_sum,3)*100,"%"))) +
  geom_pointrange(aes(xmin = val_sum_low,
                      xmax = val_sum_upp,
                      color = affpolre,
                      shape = affpolre),
                  position = position_dodge(0.8)) +
  geom_text(aes(x = val_sum + .28),
            position = position_dodge(0.8),
            size = rel(3)) +
  facet_wrap(~ var_typ, scales = "free") +
  scale_color_manual(name = "Affective Polarization",
                     values = c("#440154FF", "#2A788EFF", "#7AD151FF"),
                     guide = guide_legend(title.position = 'top')) +
  scale_shape_manual(name = "Affective Polarization",
                     values = 15:17,
                     guide = guide_legend(title.position = 'top')) +
  scale_x_continuous(labels = scales::percent,
                     limits = c(0,1),
                     breaks = c(0,.5,1)) +
  labs(x = "Percent Support",
       y = NULL) +
  theme_prl(base_family = "Helvetica") +
  theme(legend.box = 'horizontal',
        legend.direction = 'horizontal',
        axis.text.x = element_text(size = rel(.92)),
        legend.margin=margin(0,0,0,0),
        legend.box.margin=margin(-5,-5,-5,-5))

fig_3 = cowplot::plot_grid(fig_3a, fig_3b, ncol = 1, align = "v",
                              labels = c("A.", "B."))

print(fig_3)

ggsave(here("Plots","Main","figure_3.pdf"),
       fig_3,
       units = "in",
       width = 5, height = 8,
       dpi = 600)

#### Sig test for Censorship and Loyalty ####
cs_strength = data_pnas |> 
  filter(pid7 %in% c(1,7)) |>
  mutate(pid_str = case_when(
    pid7 == 1 ~ "Strong Democrat",
    pid7 == 7 ~ "Strong Republican"
  )) |>
  select(pid_str, all_of(c(norm_ind)),
         uid, weight) |> 
  as_survey_design(ids = uid, weights = weight)

strong_censor = survey::svyglm(norm_censorshipre ~ pid_str, design = cs_strength)
strong_loyalty = survey::svyglm(norm_loyaltyre ~ pid_str, design = cs_strength)

stargazer(strong_censor, strong_loyalty,
          notes = "Estimated with survey weights and two-sided tests",
          star.cutoffs = c(0.05, 0.01, 0.001),
          omit.stat = c("aic","bic"),
          ci = T,
          type = "text",
          header = F)